//
//  FQDAppearHistory.m
//  FakeQDaily
//
//  Created by mewxiv on 9/12/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDAppearHistory.h"
#import "FQDDatabase.h"

static NSString *const kAppearHistoryTableName = @"fqd_appear_history";

@implementation FQDAppearHistory


+ (instancetype)sharedHistory
{
    static FQDAppearHistory *history;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        history = [[self class] new];
    });
    return history;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    NSDictionary *columns = @{
        @"qdID" : @"VARCHAR PRIMARY KEY",
        @"appearCount" : @"INTEGER",
        @"genre" : @"INTEGER",
    };
    
    FQDDatabase *database = [FQDDatabase sharedDatabase];
    [database createTableIfNotExist:kAppearHistoryTableName columns:columns];
}

- (void)increaseAppearCountForQdID:(NSString *)qdID genre:(NSInteger)genre
{
    NSInteger appearCount = [self appearCountForQdID:qdID];
    appearCount += 1;
    
    FQDDatabase *database = [FQDDatabase sharedDatabase];
    NSDictionary *columnValues = @{
        @"qdID" : qdID,
        @"appearCount" : @(appearCount),
        @"genre" : @(genre),
    };
    [database insertOrReplaceIntoTable:kAppearHistoryTableName columnValues:columnValues];
}

- (NSInteger)appearCountForQdID:(NSString *)qdID
{
    
    NSInteger appearCount = 0;
    FQDDatabase *database = [FQDDatabase sharedDatabase];
    NSString *condition = [NSString stringWithFormat:@"qdID = '%@'", qdID];
    NSNumber *appearCountNumber = [database selectColumn:@"appearCount"
                          fromTable:kAppearHistoryTableName
                     whereCondition:condition];
    appearCount = appearCountNumber ? [appearCountNumber integerValue] : 0;
    return appearCount;
}

- (BOOL)qdIDHasAppeared:(NSString *)qdID
{
    NSInteger appearCount = [self appearCountForQdID:qdID];
    return (appearCount > 0);
}

@end
